package cn.client.ui.view.main.chat.friendApply

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.client.data.remoteData.bean.BaseResp
import cn.client.data.remoteData.bean.FriendCardItem
import cn.client.data.remoteData.bean.ReceiveFriendApply
import cn.client.data.remoteData.bean.SearchFriend
import cn.client.data.remoteData.bean.SearchFriendRes
import cn.client.data.remoteData.bean.SendFriendApply
import cn.client.data.remoteData.bean.TakeFriendApply
import cn.client.data.remoteData.repository.FriendRepository
import cn.client.ui.view.main.user.UserInfoViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class FriendApplyViewModel @Inject constructor(
    private val repository: FriendRepository
) : ViewModel() {

    /**
     * 事件管道
     */
    private val _pageEvents = Channel<PageEvent>(Channel.BUFFERED)

    /**
     * 可观察事件数据流
     */
    val pageEvents = _pageEvents.receiveAsFlow()

    /**
     * 可变状态
     */
    var pageStates by mutableStateOf(PageState())
        private set

    // 使用MutableStateFlow来存储搜索到的用户信息
    private val _friendRes = MutableStateFlow<SearchFriendRes?>(null)
    val friendRes: StateFlow<SearchFriendRes?> = _friendRes

    // 使用MutableStateFlow来存储好友申请列表
    private val _friendApplies = MutableStateFlow<List<ReceiveFriendApply>>(emptyList())
    val friendApplies: StateFlow<List<ReceiveFriendApply>> = _friendApplies

    /**
     * 收集意图
     */
    fun dispatch(intent: PageIntent){
        when(intent) {
            is PageIntent.SearchFriend -> searchFriend(intent.uid, intent.account)
            is PageIntent.SendFriendApply -> sendFriendApply(intent.uid, intent.target, intent.applyInfo)
            is PageIntent.ReceiveFriendApply -> receiveFriendApply(intent.uid)
            is PageIntent.AgreeFriendApply -> agreeFriendApply(intent.uid, intent.target)
            is PageIntent.IgnoreFriendApply -> ignoreFriendApply(intent.uid, intent.target)
            else -> {Unit}
        }
    }

    // 搜索用户
    private fun searchFriend(uid: Int, account: String ){
        viewModelScope.launch {
            val toSearch = SearchFriend(uid, account)
            try {
                val res = repository.searchFriend(toSearch)
                if (res.code==200){
                    _friendRes.value = res.data
                    _pageEvents.send(PageEvent.SearchFriend(res))
                } else {
                    val err = res.msg
                    _pageEvents.send(PageEvent.Error(err))
                    Log.d("FriendApplyViewModel","未搜到用户：$err")
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("FriendApplyViewModel","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }
    // 发送好友申请
    private fun sendFriendApply(uid: Int, target: Int, applyInfo: String? ){
        viewModelScope.launch {
            val sendApply = SendFriendApply(uid, target, applyInfo)
            try {
                val res = repository.sendFriendApply(sendApply)
                if (res.code==200){
                    _pageEvents.send(PageEvent.SendFriendApply(res))
                } else {
                    val err = res.msg
                    _pageEvents.send(PageEvent.Error(err))
                    Log.d("FriendApplyViewModel","发送失败：$err")
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("FriendApplyViewModel","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }
    // 接收好友申请
    private fun receiveFriendApply(uid: Int ){
        viewModelScope.launch {
            try {
                val res = repository.receiveFriendApply(uid)
                if (res.code==200){
                    _friendApplies.value = res.data?: emptyList()
                    _pageEvents.send(PageEvent.ReceiveFriendApplies(res))
                } else {
                    val err = res.msg
                    _pageEvents.send(PageEvent.Error(err))
                    Log.d("FriendApplyViewModel","当前没有好友申请：$err")
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("FriendApplyViewModel","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }
    // 同意好友申请
    private fun agreeFriendApply(uid: Int, target: Int ){
        viewModelScope.launch {
            val agree = TakeFriendApply(uid, target)
            try {
                val res = repository.agreeFriendApply(agree)
                if (res.code==200){
                    _pageEvents.send(PageEvent.AgreeFriendApply(res))
                } else {
                    val err = res.msg
                    _pageEvents.send(PageEvent.Error(err))
                    Log.d("FriendApplyViewModel","操作失败：$err")
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("FriendApplyViewModel","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }
    // 忽略好友申请
    private fun ignoreFriendApply(uid: Int, target: Int ){
        viewModelScope.launch {
            val ignore = TakeFriendApply(uid, target)
            try {
                val res = repository.ignoreFriendApply(ignore)
                if (res.code==200){
                    _pageEvents.send(PageEvent.IgnoreFriendApply(res))
                } else {
                    val err = res.msg
                    _pageEvents.send(PageEvent.Error(err))
                    Log.d("FriendApplyViewModel","操作失败：$err")
                }
            } catch (e: Exception) {
                val errors = PageEvent.Error(e.localizedMessage ?: "UnKnown Error")
                Log.d("FriendApplyViewModel","程序发生异常：$e")
                _pageEvents.send(errors)
            }
        }
    }


    /**
     * 意图集
     */
    sealed class PageIntent {
        data class SearchFriend(val uid: Int, val account: String): PageIntent()
        data class SendFriendApply(val uid: Int, val target: Int, val applyInfo: String?): PageIntent()
        data class ReceiveFriendApply(val uid: Int): PageIntent()
        data class AgreeFriendApply(val uid: Int, val target: Int): PageIntent()
        data class IgnoreFriendApply(val uid: Int, val target: Int): PageIntent()
    }

    /**
     * 事件集
     */
    sealed class PageEvent {
        object Idle: PageEvent()
        data class SearchFriend(val res: BaseResp<SearchFriendRes>): PageEvent()
        data class SendFriendApply(val res: BaseResp<Any>): PageEvent()
        data class ReceiveFriendApplies(val res: BaseResp<List<ReceiveFriendApply>>): PageEvent()
        data class AgreeFriendApply(val res: BaseResp<Any>): PageEvent()
        data class IgnoreFriendApply(val res: BaseResp<Any>): PageEvent()
        data class Error(val error: String): PageEvent()
    }

    /**
     * 状态集
     */
    data class PageState(
        val uid: Int = -1,
        val friendId: Int = -1,
        val friendAvatar: String = ""
    )


}